import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入Login组件
import Login from '../components/Login'
// 引入Home组件
import Home from '../components/Home'
// 引入Welcome组件
import Welcome from '../components/Welcome'
import UserList from '../components/admin/UserList'

Vue.use(VueRouter)

const routes = [
  // 路由配置
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    component: Login
  },
  {
    path: "/home",
    component: Home,
    redirect: "/welcome",
    children: [
      {
        path: "/welcome",
        component: Welcome
      },
      { 
        path: "/user", 
        component: UserList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
    // to 将要访问 | from 从哪跳转 | next 接着要干什么
    // 首页放行
    if(to.path == "/login") return next();
    // 获取user
    const userFlag = window.sessionStorage.getItem("user");
    if(!userFlag) return next('/login'); // 用户未登录，重定向到登录页
    next();
})

export default router
